<?php
/**
 * AJAX Handler for Projects: Add - Adding a project to the database
 * 
 * I have made sure Libdebug is silent in AJAX. This is because it can intefere with the HTML/Javascript as Libdebug Appends after </html>.
 * If you have a problem and need to debug comment $_LIBDEBUG->silence(); (the framework must also be in debugging mode for this to work)
 */


    require_once('../../SiteIncludes.GLOBAL.php');
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	header('HTTP/1.1 400 Bad Request');
	die($nok_caller);
    }
    
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($pVAR['hidden_text_alias']) === true && isset($pVAR['add_name']) === true && isset($pVAR['add_desc']) === true) {
	$match = preg_match('/^([a-z0-9_]+)?([a-z]+)([a-z0-9_]+)?$/i', $pVAR['hidden_text_alias']);
	if($match) {
	    try {
		$ProjectStash->get($pVAR['hidden_text_alias']);
		echo <<<EOE
		    <!DOCTYPE html>
			<html>
			    <head><title></title></head>
			    <body>
				<script type="text/javascript">
				    parent.EDJXConfirmer.show_nok();
				    parent.NewProject.alreadyTaken('That name is already taken: <a href="/add/project">Start Again</a>');
				</script>
			    </body>
			</html>
EOE;
	    } catch(InvalidProjectException $e) {
		if(strlen($pVAR['hidden_text_alias']) < 32 && strlen($pVAR['add_name']) < 128) {
		    $safe_name = $sql_conx->real_escape_string($pVAR['add_name']);
		    $safe_alias = $sql_conx->real_escape_string($pVAR['hidden_text_alias']);
		    $safe_desc = $sql_conx->real_escape_string($pVAR['add_desc']);
		    $now = time();
		    $query = $sql_conx->query("INSERT INTO `tool_project` ( `pid` , `name` , `alias` , `description` , `icon_url` , `lead_maintainer` , `creation_time` , `lastedit_time` , `visible` ) VALUES ( NULL ,  '{$safe_name}',  '{$safe_alias}',  '{$safe_desc}',  '',  '{$_LOGGEDINUSER->get_userid()}',  '{$now}',  '{$now}',  '0' )");
		    if($sql_conx->affected_rows === 0) {
			$cb_scripts = <<<EOC
			parent.EDJXConfirmer.show_nok();
			parent.NewProject.alreadyTaken('Something went wrong with our end, please try again later.');
EOC;
		    } else {
			$cb_scripts = <<<EOC
			parent.EDJXConfirmer.show_ok();
			parent.NewProject.alreadyTaken(false);
			parent.NewProject.add_callback(true);
EOC;
		    }
		} else {
		    $cb_scripts = <<<EOC
			parent.EDJXConfirmer.show_nok();
			parent.NewProject.alreadyTaken('Your name or alias is over the maximum character limit.');
EOC;
		}
		echo <<<EOE
		    <!DOCTYPE html>
			<html>
			    <head><title></title></head>
			    <body>
				<script type="text/javascript">
				    {$cb_scripts}
				</script>
			    </body>
			</html>
EOE;
	    }
	}
    } else {
	header('HTTP/1.1 400 Bad Request');
	die($nok_caller);
    }
?>